package com.zhao.customer.dao;

import com.zhao.customer.entity.User;
import com.zhao.customer.util.DBUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class UserDao {
    public User selectByName(String name) throws Exception {
        String sql = "select name,password from myuser where name=?";
        List<Map<String, String>> list = DBUtil.query(sql, name);
        User user = null;
        for (Map<String, String> map: list) {
            user = new User(map.get("name"),map.get("password"));
        }
        return  user;
    }

    public User selectById(int id) throws Exception {
        String sql = "select id,name,password from myuser where id=?";
        List<Map<String, String>> list = DBUtil.query(sql, id);
        User user = null;
        for (Map<String, String> map: list) {
            user = new User(Integer.parseInt(map.get("id")),map.get("name"),map.get("password"));
        }
        return  user;
    }

    public int count() {
        String sql = "select count(id) from myuser";
        List<Map<String, String>> list = DBUtil.query(sql);

        //System.out.println();
        return Integer.parseInt(list.iterator().next().get("count(id)"));
    }

    public List<User> selectAll() throws Exception {
        String sql = "select * from myuser ";
        List<Map<String, String>> list = DBUtil.query(sql);
        List<User> users = new LinkedList<>();
        User user = null;
        for (Map<String, String> map: list) {
            user = new User(Integer.parseInt(map.get("id")),map.get("name"),map.get("password"));
            /*user.setId(Integer.parseInt(map.get("id")));
            user.setName(map.get("name"));
            user.setPassword(map.get("password"));*/
            users.add(user);
        }
        return  users;
    }

    public List<User> selectByPage(int page, int size) throws Exception {
        String sql = "select * from myuser limit ?,?";
        List<Map<String, String>> list = DBUtil.query(sql, (page-1)*size, size);
        List<User> users = new LinkedList<>();
        User user = null;
        for (Map<String, String> map: list) {
            user = new User(Integer.parseInt(map.get("id")),map.get("name"),map.get("password"));
            /*user.setId(Integer.parseInt(map.get("id")));
            user.setName(map.get("name"));
            user.setPassword(map.get("password"));*/
            users.add(user);
        }
        return  users;
    }

    public void save(User user){
        String sql = "insert into myuser (name, password) values (?,?)";
        String[] ss = {user.getName(), user.getPassword()};
        DBUtil.update(sql,ss);//这个方法可以完成增删改
    }

    public void update(User user) {
        String sql = "update myuser set name=?, password=? where id=?";
        Object[] ss = { user.getName(), user.getPassword(), user.getId()};
        DBUtil.update(sql,ss);
    }
}
